package com.iuie.ns.system.controller.login;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.iuie.ns.frame.utils.DeviceUtil;
import com.iuie.ns.frame.utils.ShiroUtils;
import com.iuie.ns.frame.utils.StringUtils;
import com.iuie.ns.frame.utils.TreeUtils;
import com.iuie.ns.frame.utils.WebUtils;
import com.iuie.ns.frame.web.response.vo.ResponseInfo;
import com.iuie.ns.system.service.loginlog.ISysLoginLogService;
import com.iuie.ns.system.service.user.ISysUserService;
import com.iuie.ns.system.shiro.realm.MyShiroRealm;
import com.iuie.ns.system.vo.login.SysLoginLogVO;
import com.iuie.ns.system.vo.login.SysLoginLogVO.Builder;
import com.iuie.ns.system.vo.resource.SysResourceVO;
import com.iuie.ns.system.vo.role.SysRoleVO;
import com.iuie.ns.system.vo.user.SysUserVO;

/**
 * 
 * @description 系统用户登录的控制器
 * @author lj
 * @createTime 2016年8月23日 上午11:50:09
 */
@Controller
@RequestMapping
public final class SysLoginController {
	
	@Resource
	private MyShiroRealm myRealm;

    @Resource
    private ISysUserService userService;
    
    @Resource
    private ISysLoginLogService loginLogService;

	/**
	 * 系统用户登录系统的方法
	 * @param request
	 * @param resp
	 * @param model
	 * @return
	 * @date 2017年6月11日 下午3:09:12
	 */
	@RequestMapping(value = "{login:login;?.*}")
	public String login(HttpServletRequest request, HttpServletResponse resp, Model model) {
	    
	    String exceptionClassName = (String)request.getAttribute("shiroLoginFailure");
	    String error = null;
	    String errorType = null; // 错误类型
        if(UnknownAccountException.class.getName().equals(exceptionClassName)) {
            error = "用户名/密码错误";
            errorType = "accountError";
        } else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
            error = "用户名/密码错误";
            errorType = "accountError";
        } else if("randomCodeError".equals(exceptionClassName)) {
            error = "验证码错误";
            errorType = "randomCodeError";
        }else if(LockedAccountException.class.getName().equals(exceptionClassName)){
            error="用户已被禁止登录";
        }
        model.addAttribute("error", error);
        model.addAttribute("errorType", errorType);
        Subject subject= SecurityUtils.getSubject();
        Session session=subject.getSession();
        Object s= session.getAttribute("user");
        if(s!=null){
            subject.logout();
        }
        return "view-system/login/login";
	}
	
	/**
	 * 进入系统首页
	 * @return
	 * @date 2017年6月11日 下午3:30:37
	 */
	@RequestMapping(value = {"/index", "/"})
	public String index(HttpServletRequest request, String roleId){
	    HttpSession session = request.getSession();
	    SysUserVO user = (SysUserVO) session.getAttribute("user");
	    // 判定切换角色
	    if (roleId == null) {
	    	
	    } else {
	    	Set<SysRoleVO> roles = user.getRoles();
	    	Iterator<SysRoleVO> it = roles.iterator();
	    	if (roles == null || roles.size() == 0) {
	    		return "view-system/index/index";
	    	}
	    	while (it.hasNext()) {
	    		SysRoleVO role = it.next();
	    		if (StringUtils.equals(roleId, role.getRoleId())) {
	    			user.setCurrentRole(role);
	    			Subject subject=SecurityUtils.getSubject();
	    			SimplePrincipalCollection pl = (SimplePrincipalCollection) subject.getPrincipals();
					myRealm.clearCachedAuthorizationInfo(pl);
					// 切换角色：1.更新登录角色，2.返回全量用户信息
					userService.updateCurrentRole(user, role);
					SysUserVO nuser = userService.findByIdWithWhole(user.getUserId());
					session.setAttribute("user", nuser);
					
					// 记录登录日志
					Builder builder = new SysLoginLogVO.Builder();
					SysLoginLogVO log = builder.build(nuser.getUserId(), user.getCurrentRole().getRoleId(), WebUtils.getIP(request));
					loginLogService.addOne(log);
	    		}
	    	}
	    }
	    
	    SysUserVO nuser = (SysUserVO) session.getAttribute("user");
	    if (nuser.getCurrentRole() != null) {
	    	Set<SysResourceVO> resources = nuser.getCurrentRole().getResources();
	    	List<SysResourceVO> trees = TreeUtils.buildTree(resources, null);
	    	request.setAttribute("menus", trees);
	    }
	    return toIndex(request);
	}
	
	private String toIndex(HttpServletRequest request) {
		if (DeviceUtil.isMobile(request)) {
			return "view-system/index/m_index";
		}
		return "view-system/index/index";
	}
	
	/**
	 * 修改密码index
	 * @param request
	 * @return
	 * @date 2017年8月6日 下午1:36:54
	 */
	@RequestMapping(value = "/index/updatePwd")
	public String updatePwdIndex() {
		return "view-system/index/updatePwd";
	}
	
	/**
	 * 修改密码
	 * @return
	 * @date 2017年8月6日 下午1:37:56
	 */
	@RequestMapping(value = "/updatePwd", method=RequestMethod.POST)
	@ResponseBody
	public ResponseInfo updatePwd(String userPwd) {
		SysUserVO user = (SysUserVO) ShiroUtils.getCurrentUser();
		userService.updateUserPwd(user.getUserId(), userPwd);
		return ResponseInfo.successInfo("密码修改成功，请牢记你的密码！");
	}
	
	/**
	 * 切换角色index
	 * @return
	 * @date 2017年8月6日 下午6:31:42
	 */
	@RequestMapping(value = "/index/switchRole")
	public String switchRoleIndex(HttpServletRequest request) {
		return "view-system/index/switchRole";
	}
	
	
	@RequestMapping(value = "/heartBeat/{timestamp}")
	@ResponseBody
	public String heartBeat(@PathVariable("timestamp") String timestamp){
		return null;
	}

}
